package com.media.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class LoginListener implements ServletContextListener,HttpSessionListener, HttpSessionAttributeListener {

    // Public constructor is required by servlet spec
    public LoginListener() {
    }

    public void contextInitialized(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        application.setAttribute("userCount",0);
    }

    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("servlet context 初始化");
    }

    public void sessionCreated(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        int userCount = (int)application.getAttribute("userCount");
        userCount++;
        application.setAttribute("userCount",userCount);

        System.out.println("session 创建，新用户登录,当前用户人数"+userCount);
    }

    public void sessionDestroyed(HttpSessionEvent se) {

        ServletContext application = se.getSession().getServletContext();
        int userCount = (int)application.getAttribute("userCount");
        if(userCount>0){
            userCount--;
        }else{
            userCount = 0;
        }
        application.setAttribute("userCount",userCount);

        System.out.println("session 创建，用户注销,当前用户人数"+userCount);
    }

    public void attributeAdded(HttpSessionBindingEvent sbe) {
        System.out.println("session 设置属性");
    }

    public void attributeRemoved(HttpSessionBindingEvent sbe) {
        System.out.println("session 移除属性");
    }

    public void attributeReplaced(HttpSessionBindingEvent sbe) {
        System.out.println("session 属性更改");
    }
}
